package com.charles.seckillcommon.security.interceptor;

import com.charles.seckillapi.model.UserLogin;
import com.charles.seckillcommon.core.constants.RoleConstants;
import com.charles.seckillcommon.core.context.ThreadContext;
import com.charles.seckillcommon.core.utils.ServletUtils;
import com.charles.seckillcommon.security.utils.ThreadUtil;
import com.charles.seckillcommon.security.utils.auth.AuthVerifyUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Charles-H
 * 
 * 请求头拦截器
 */
@Component
public class HeaderInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;

        /* 每一次请求时，都进入拦截器，将客户登录信息丢入线程中 */
        ThreadContext.setUserId(ServletUtils.getHeader(request, RoleConstants.USER_ID));
        ThreadContext.setUserKey(ServletUtils.getHeader(request, RoleConstants.USER_KYE));
        ThreadContext.setUsername(ServletUtils.getHeader(request, RoleConstants.USERNAME));
        ThreadContext.setUserCard(ServletUtils.getHeader(request, RoleConstants.USER_CARD));

        String token = ThreadUtil.getToken();
        if (token != null && !token.isEmpty()) {
            UserLogin userLogin = AuthVerifyUtil.getUserLogin(token);
            if (userLogin != null) {
                AuthVerifyUtil.checkUserLogin(userLogin);
                ThreadContext.set(RoleConstants.USER_LOGIN, userLogin);
            }
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        /* 移除线程 */
        ThreadContext.removeThread();
    }

}
